<?php
namespace App\Services;

use Illuminate\Http\Client\RequestException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Illuminate\Support\Facades\Http;

class AdminService {
    /**
     * @notes 发起公共请求
     * @param $path
     * @param $data
     * @param $header
     * @return mixed
     * @throws RequestException
     * @author Evil丿
     * @date 2024/06/06 15:33
     */
    private static function commonRequest($path, $data, $method = "GET", $header = [])
    {
        if(strpos($path, 'http') === false) {
            $host = config('services.shop_admin.url');
            $url = $host . $path;
        } else {
            $url = $path;
        }

        if($method == "POST") {
            $response = Http::retry(3, 1000)
                -> timeout(5)
                -> withHeaders($header)
                -> post($url, $data)
                -> throw()
                -> json();

        } else {
            $response = Http::retry(3, 1000)
                -> timeout(5)
                -> withHeaders($header)
                -> get($url, $data)
                -> throw()
                -> json();
        }

        if(!$response) {
            throw new AccessDeniedHttpException('商城服务请求失败');
        }

        if($response['code'] != 1) {
            throw new AccessDeniedHttpException($response['msg']);
        }

        return $response;
    }

    public static function getUserInfo(string $mobile) : array {

        $params = [
            "mobile" => $mobile
        ];

        $path = '/api/v1.user/getUserInfoByMobile';

        $res = self::commonRequest($path, $params);

        return $res;
    }
}
